<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 角色添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">角色添加</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表table -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
            :class="['bd-bottom','vcenter',i1 === 0?'bd-top':'']">
               <!-- 一级权限 -->
              <el-col :span="5">
               <el-tag @close="removeRoleById(scope.row,item1.id)" closable> {{item1.authName}}</el-tag>
               <i class="el-icon-caret-right"></i>
              </el-col>
                <!-- 二、三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id"
                :class="[i2 === 0 ?'':'bd-top','vcenter']">
                  <!-- 二级权限的渲染 -->
                  <el-col :span="6">
                    <el-tag @close="removeRoleById(scope.row,item2.id)" closable type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限的渲染 -->
                  <el-col :span="18">
                    <el-tag @close="removeRoleById(scope.row,item3.id)" closable type="warning" v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 普通列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose">
      <!-- 树形控件 -->
      <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"
      ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {

  data() {
    return {
      roleList: [],
      setRightDialogVisible: false,
      rightList: [],
      treeProps: {
          children: 'children',
          label: 'authName'
      },
      // 默认树形结构选中节点
      defKeys: [],
      // 当前角色的id
      roleId: ''
    }
  },

  created() {
    // a:获取角色列表数据
    this.getRolesList()
  },

 methods: {
    async getRolesList() {
      const { data: res } = await this.$html.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      // 获取角色列表数据成功
      this.roleList = res.data
    },
    async removeRoleById(role, rightId) {
     const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      // 确认删除
      const { data: res } = await this.$html.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
          return this.$message.error('删除失败！')
      }
      // 删除成功，重新赋值role.children实现局部跟新
      role.children = res.data
    },
    // 展示“分配权限”对话框
    async showSetRightDialog(role) {
      // 获取所有权限列表
      const { data: res } = await this.$html.get('rights/' + 'tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取所有权限列表失败！')
      }
      // 获取权限列表成功
      this.rightList = res.data
      // 获取默认展示的子节点
      this.getLeafKeys(role, this.defKeys)
      // a2:获取当前角色的id
      this.roleId = role.id
      // 展示对话框
      this.setRightDialogVisible = true
    },
    // 获取三级节点
    getLeafKeys(node, arr) {
      // 如果不存在子节点，则为三级节点（最后一个节点）
      if (!node.children) {
        return arr.push(node.id)
      }
      // 不是三级节点
      node.children.forEach(item => {
        return this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限弹框关闭
    setRightDialogClose() {
      this.defKeys = []
    },
    // 分配权限弹框确认按钮的监听
    async allotRight() {
      // a:完成角色权限的上传
      // a1：获取上传需要的参数role.id和权限 ID 列表
      // a3：获取 权限 ID 列表
      const arr1 = this.$refs.treeRef.getCheckedKeys()
      const arr2 = this.$refs.treeRef.getHalfCheckedKeys()
      const keys = [...arr1, ...arr2]
      const keysStr = keys.join(',')
      // a4:调用接口完成上传
      const { data: res } = await this.$html.post(`roles/${this.roleId}/rights`, {
        rids: keysStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('角色授权失败！')
      }
      // 角色授权成功
      this.$message.success('角色授权成功！')
      // 刷线角色列表
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-top {
  border-top: 1px solid #eee;
}
.bd-bottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>